package com.sh.expend;



import com.sh.bean.CommonInformationItem;
import com.sh.bean.RssNewsBuffer;
import com.sh.utils.ProjectProperties;
import org.apache.log4j.Logger;
import java.io.BufferedWriter;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;

/**
 * 消费者
 * 新闻从缓存中拿数据写入磁盘|数据库|mongodb任务
 */
public class NewsWriterTask implements Runnable {

    private static Logger log = Logger.getLogger(NewsWriterTask.class.getName());
    private String name;  // rss的源名称，做磁盘文件的文件名
    private RssNewsBuffer buffer;  // 缓存队列所在的类
    private boolean flag = false;  // 标记是否结束

    public NewsWriterTask(RssNewsBuffer buffer) {
        this.buffer = buffer;
        this.name = "未知新闻源";
    }

    public NewsWriterTask(RssNewsBuffer buffer, String name) {
        this.buffer = buffer;
        this.name = name;
    }


    @Override
    public void run() {
        System.out.println("消费者开始");
        // 循环从缓存中取数据，写入磁盘|数据库|mongodb
        while (!flag && !Thread.currentThread().isInterrupted()) {
            // 获取缓存中的数据
            CommonInformationItem item = buffer.get();
            if (item == null) {
                continue;
            }
            // 写入磁盘|数据库|mongodb
            String userDir = System.getProperty("user.dir");
            ProjectProperties instance = ProjectProperties.getInstance();
            String property = instance.getProperty("file.path") + item.getFileName();
            String endPath = userDir + property;
//            System.out.println(property);
            Path p = Paths.get(endPath);

            try (
                    // 一个缓冲字符流  可以一行一行写
                    BufferedWriter writer = Files.newBufferedWriter(p, StandardOpenOption.CREATE)
            ) {
                writer.write(item.toString());
                writer.flush();
            } catch (Exception e) {
                log.error("写入文件失败", e);
                e.printStackTrace();
            }


        }
    }

}
